package logic

import (
	"ball/ballrpc/ballrpc"
	"ball/ballrpc/internal/svc"
	"ball/cache"
	"ball/models/mysql"
	"context"
	"encoding/json"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type TopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewTopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TopListLogic {
	return &TopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// top10排行榜
func (l *TopListLogic) TopList(in *ballrpc.TopListRequest) (*ballrpc.TopListResponse, error) {
	// todo: add your logic here and delete this line
	var talk []mysql.Talk

	result, _ := cache.Rdb.Get(l.ctx, "Toplist").Result()
	if result == "" {
		mysql.DB.Debug().Limit(10).Find(&talk)
		marshal, _ := json.Marshal(&talk)
		cache.Rdb.Set(l.ctx, "Topliat", marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &talk)
	}

	var TopList []*ballrpc.TopList
	for _, m := range talk {
		list := ballrpc.TopList{
			Image: m.Image,
			Name:  m.Name,
			Price: m.Price,
		}
		TopList = append(TopList, &list)
	}
	return &ballrpc.TopListResponse{
		List: TopList,
	}, nil
}
